package com.appspot.igo8poi.model.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import com.appspot.igo8poi.model.bean.Poi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@SuppressWarnings({"unchecked"})
@Repository
public class PoiDao extends BaseDao {

	@Autowired
	public PoiDao(PersistenceManagerFactory pmf) {
		super(pmf);
	}

	private List<Poi> getPois(PersistenceManager pm, String userId) {
		String query = "select from " + Poi.class.getName();
		query += " where userId == :userId";
		query += " order by groupName asc, number asc";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		return (List<Poi>) pm.newQuery(query).executeWithMap(params);
	}

	public List<Poi> getPois(String userId) {
		return getPois(getPersistenceManager(), userId);
	}

	public boolean deletePoi(String userId, Poi poi) {
		if (null == poi || null == userId || !userId.equals(poi.getUserId())) {
			return false;
		}
		getPersistenceManager().deletePersistent(poi);
		return true;
	}

	public Poi savePoi(Poi poi) {
		return savePoi(getPersistenceManager(), poi);
	}

	private Poi savePoi(PersistenceManager pm, Poi poi) {
		if (null == poi.getUserId()) {
			return null;
		}

		return pm.makePersistent(poi);
	}

	public Collection<Poi> savePois(Collection<Poi> pois) {
		return savePois(getPersistenceManager(), pois);
	}

	private Collection<Poi> savePois(PersistenceManager pm, Collection<Poi> pois) {
		return pm.makePersistentAll(pois);
	}

}
